﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Linq.Expressions;
using Microsoft.Extensions.DependencyInjection;

namespace Lrd.Permissions.Common
{
    public class ModulePackManager : IModulePackManager
    {
        public ModulePackManager()
        {
            SourcePacks = new List<ModulePack>();
            LoadedPacks = new List<ModulePack>();
        }
        public List<ModulePack> SourcePacks { get; private set; }

        public List<ModulePack> LoadedPacks { get; private set; }

        public IServiceCollection LoadPacks(IServiceCollection services)
        {
            var baseType = typeof(ModulePack);
            var packTypes = GetType().Assembly.GetTypes().Where(o => o.IsClass && baseType.IsAssignableFrom(o) && !o.IsAbstract).Distinct().ToArray();
            SourcePacks.Clear();

            //var newPack= Expression.Lambda(Expression.New(baseType)).Compile().DynamicInvoke();
            SourcePacks.AddRange(packTypes.Select(m => (ModulePack)Activator.CreateInstance(m)));
            List<ModulePack> packs=SourcePacks.ToList();
            packs = packs.OrderBy(m => m.Order).ToList();
            LoadedPacks = packs;

            foreach (var pack in LoadedPacks)
            {
                services = pack.AddServices(services);
            }
            return services;
        }

        public void UsePack(IServiceProvider provider)
        {
            foreach (var pack in LoadedPacks)
            {
                pack.UsePack(provider);
            }
        }


    }
}
